<?php

function build_rules_table($program_id, $rules) {
    global $high_schools, $ngos, $rules_subjects, $subjects;
    $has_errors = false;
    echo "<table border=1 style='border-collapse:collapse' cellpadding=2>";
    echo "<tr><th></th><th>Rule type</th><th>Rule</th><th>Apply to</th><th>Projection</th></tr>";
    foreach ($rules as $rule) {
        $global_avg = "";
        $rule_id = $rule["exam_eligibility_rule_id"];
        $rule_subjects = $rules_subjects[$rule_id];

        $error = null;
        if ($rule_subjects == false || count($rule_subjects) == 0) {
            $error = "No subject selected. Please add one.";
            $type = "";
        } else if ($rule["apply_to_high_school_id"] == null && $rule["apply_to_ngo_id"] == null) {
            // general rule
            $type = "General";
            $color = "#FFFFFF";
            // check no other similar general rule
            foreach ($rules as $r) {
                if ($r == $rule)
                    continue;
                if ($r["apply_to_high_school_id"] <> null)
                    continue;
                if ($r["apply_to_ngo_id"] <> null)
                    continue;
                if ($r["type"] <> $rule["type"])
                    continue;
                if (same_subjects($rule_subjects, $rules_subjects[$r["exam_eligibility_rule_id"]])) {
                    $error = "Another general rule exist with the same subjects";
                    break;
                }
            }
        } else {
            // exception
            $type = "Exception";
            $color = "#A0C0A0";
            // check a general rule exists
            $found = false;
            foreach ($rules as $r) {
                if ($r == $rule)
                    continue;
                if ($r["apply_to_high_school_id"] <> null)
                    continue;
                if ($r["apply_to_ngo_id"] <> null)
                    continue;
                if ($r["type"] <> $rule["type"])
                    continue;
                if (same_subjects($rule_subjects, $rules_subjects[$r["exam_eligibility_rule_id"]])) {
                    $found = true;
                    break;
                }
            }
            if (!$found)
                $error = "No general rule corresponding to this exception.<br/>Please create a general rule with the same subjects or modify the subjects of this rule";
            else {
                // check exactly the same exception do not exist
                foreach ($rules as $r) {
                    if ($r == $rule)
                        continue;
                    if ($r["apply_to_high_school_id"] == null && $r["apply_to_ngo_id"] == null)
                        continue;
                    if ($r["apply_to_high_school_id"] <> $rule["apply_to_high_school_id"])
                        continue;
                    if ($r["apply_to_ngo_id"] <> $rule["apply_to_ngo_id"])
                        continue;
                    if ($r["type"] <> $rule["type"])
                        continue;
                    if (same_subjects($rule_subjects, $rules_subjects[$r["exam_eligibility_rule_id"]])) {
                        $error = "The same exception already exist.<br/>Please modify the subjects, or high school/NGO to make it different.";
                        break;
                    }
                }
            }
        }
        if ($error <> null) {
            $color = "#C0A0A0";
            $has_errors = true;
        }

        echo "<tr style='background-color:" . $color . "'>";
        echo "<td><a href='?program_number=".$_GET["program_number"]."&remove_rule=" . $rule_id . "'><img src='" . $_SESSION["root_url"] . "/images/trash.gif' border=0/></a></td>";
        echo "<td valign='top'><a name='rule" . $rule_id . "'>";
        echo $type . "<br/>";
        echo "<select onchange=\"location.href='?change_rule_type='+this.value+'&rule=" . $rule_id . "#rule" . $rule_id . "';\">";
        echo "<option value='0'";
        if ($rule['type'] == 0)
            echo " selected='selected'";
        echo ">Minimum</option>";
        echo "<option value='1'";
        if ($rule['type'] == 1)
            echo " selected='selected'";
        echo ">Threshold</option>";
        echo "</select>";
        echo "</a></td><td>";
        if ($error <> null)
            echo "<span style='color:red'>" . $error . "</span><br/>";
        $remaining_subjects = array();
        foreach ($subjects as $s)
            array_push($remaining_subjects, $s);
        $nb_applicants = 0;

        if ($rule_subjects <> false && count($rule_subjects) > 0) {
            $global_mark = 0;
            
            echo "Mark of ";
           //if(count($rule_subjects) > 1) {
                for ($i = 0; $i < count($rule_subjects); $i++) {
                    if ($i > 0)
                        echo " + ";
                    foreach ($subjects as $s)
                        if ($s["subject_id"] == $rule_subjects[$i]["subject_id"]) {
                            echo $s["subject_name"];
                            $global_mark += $s["global_mark"];
                            for ($j = 0; $j < count($remaining_subjects); $j++)
                                if ($remaining_subjects[$j]["subject_id"] == $s["subject_id"]) {
                                    array_splice($remaining_subjects, $j, 1);
                                    break;
                                }
                            break;
                        }
                    echo "<a href='?remove_subject=" . $rule_subjects[$i]["subject_id"] . "&rule=" . $rule_id . "#rule" . $rule_id . "'><img src='" . $_SESSION["root_url"] . "/images/small_remove.gif' border=0 hspace=0 vspace=0 style='vertical-align:middle'/></a>";
                    //echo "<br/>";
                }
                echo " = ";
                echo "<input id='mark_rule_" . $rule_id . "' type='text' size=6 value='" . $rule["mark"] . "' onblur=\"location.href='?mark='+this.value+'&rule=" . $rule_id . "#rule" . $rule_id . "';return false\"/>";
                echo " / " . $global_mark;
                echo "<br/>";

                if(count($rule_subjects) > 1) {
                  
                    $sum_avg = 0;
                    for($k=0;$k<count($rule_subjects);$k++){
                        $one_subject_array = array();
                        $one_subject_array[0]["subject_id"] = $rule_subjects[$k]["subject_id"];
                        $res2 = calculate_avg_min_max($rule, $one_subject_array, $program_id);
                        
                        $sum_avg += $res2[0];

                    }
                    if ($res2 <> false)
                        $nb_applicants = $res2[3];
                    echo  "<i>AVG= ".$sum_avg ." </i><a href='' onclick=\"use_formula('" . $sum_avg . "'," . $rule_id . ");return false\">use formula</a> <br/>";
                } else {
                    $res = calculate_avg_min_max($rule, $rule_subjects, $program_id);
                    //echo $rule_subjects [0][1] ;
                    if ($res <> false)
                        $nb_applicants = $res[3];
                    if ($res <> false)
                        echo "<i>AVG=" . $res[0] . " MIN=" . $res[1] . " MAX=" . $res[2] . "</i> <a href='' onclick=\"use_formula('" . $res[0] . "'," . $rule_id . ");return false\">use formula</a><br/>";
                }

        }

        if (count($remaining_subjects) > 0) {
            echo "Add a subject in the rule:<select name='add_subject_" . $rule_id . "'>";
            foreach ($remaining_subjects as $s)
                echo "<option value='" . $s["subject_id"] . "'>" . $s["subject_name"] . "</option>";
            echo "</select><button onclick=\"var sid=document.forms['rules_" . $program_id . "'].elements['add_subject_" . $rule_id . "'].value;location.href='?add_subject='+sid+'&rule=" . $rule_id . "#rule" . $rule_id . "';return false\">Add</button>";
        }
        echo "</td>";
        echo "<td valign='top'>";
        echo "High school:";
        echo "<select onchange=\"location.href='?apply_rule_to_high_school='+this.value+'&rule=" . $rule_id . "#rule" . $rule_id . "'\">";
        echo "<option value='NULL'" . ($rule["apply_to_high_school_id"] == null ? " selected='selected'" : "") . ">All</option>";
        foreach ($high_schools as $hs)
            echo "<option value='" . $hs["high_school_id"] . "'" . ($rule["apply_to_high_school_id"] == $hs["high_school_id"] ? " selected='selected'" : "") . ">" . $hs["high_school_name"] . "</option>";
        echo "</select><br/>";
        if ($rule["apply_to_high_school_id"] == null) {
            $excluded = get_excluded_high_schools($rule, $rule_subjects, $program_id);
            if (count($excluded) > 0) {
                echo "Except ";
                $s = "";
                foreach ($excluded as $hs_id => $hs_name) {
                    if ($s <> "")
                        $s.=",";
                    $s.=$hs_name;
                }
                echo $s;
                echo "<br/>";
            }
        }
        echo "NGO:";
        echo "<select onchange=\"location.href='?apply_rule_to_ngo='+this.value+'&rule=" . $rule_id . "#rule" . $rule_id . "'\">";
        echo "<option value='NULL'" . ($rule["apply_to_ngo_id"] == null ? " selected='selected'" : "") . ">Everybody</option>";
        foreach ($ngos as $ngo)
            echo "<option value='" . $ngo["ngo_id"] . "'" . ($rule["apply_to_ngo_id"] == $ngo["ngo_id"] ? " selected='selected'" : "") . ">" . $ngo["ngo_name"] . "</option>";
        echo "</select><br/>";
        if ($rule["apply_to_ngo_id"] == null) {
            $excluded = get_excluded_ngos($rule, $rule_subjects, $program_id);
            if (count($excluded) > 0) {
                echo "Except ";
                $s = "";
                foreach ($excluded as $ngo_id => $ngo_name) {
                    if ($s <> "")
                        $s.=",";
                    $s.=$ngo_name;
                }
                echo $s;
                echo "<br/>";
            }
        }
        echo "</td>";
        echo "<td valign='top'>";
        $nbSatisfy = nb_applicants_satisfying_rule($rule, $rule_subjects, $program_id);
        echo $nbSatisfy . "/" . $nb_applicants . " applicants (" . percent($nbSatisfy, $nb_applicants) . ")<br/>fulfill this rule";
        echo "</td>";
        echo "</tr>";
    }
   
    echo "</table>";
    return!$has_errors;
}

?>
